package wsz.user.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import wsz.pojo.Token;
import wsz.user.service.UserService;
import wsz.util.CommonUtils;
import wsz.util.ConstantsUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wsz
 * @date 2021/12/27 12:44
 **/
@RestController
@RequestMapping(value = "user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param email
     * @param password
     * @return email
     */
    @GetMapping(value = "login/{email}/{password}")
    public String login(@PathVariable(name = "email") String email, @PathVariable(name = "password") String password, HttpServletResponse response) {
        Token token = userService.findByEmailAndPwd(email, password);
        if (token == null) {
            return ConstantsUtils.DEFAULT_ERROR;
        }
        // 生成token+cookie
        String randomToken = CommonUtils.getRandomString();
        Cookie cookie = new Cookie(ConstantsUtils.TOKEN, randomToken);
        cookie.setPath("/");
        response.addCookie(cookie);
        // 登录后更新token
        token.setToken(randomToken);
        userService.modify(token);

        return token.getEmail();
    }

    /**
     * 获取人员信息
     * @param token
     * @return
     */
    @GetMapping(value = "info/{token}")
    public String info(@PathVariable(name = "token") String token) {
        Token user = userService.findByToken(token);
        if (user == null) {
            return "-1";
        }
        return user.getEmail();
    }

    /**
     * 注册
     * @param email
     * @param password
     * @param code
     * @return
     */
    @GetMapping(value = "register/{email}/{password}/{code}")
    public int register(@PathVariable(name = "email") String email,
                            @PathVariable(name = "password") String password,
                            @PathVariable(name = "code") String code) {
        return userService.register(email, password, code);
    }

    /**
     * 是否已注册
     * @param email
     * @return
     */
    @GetMapping(value = "isRegistered/{email}")
    public boolean isRegistered(@PathVariable(name = "email") String email) {
        return userService.isRegistered(email);
    }
}
